package common

import "sync"

//contextor 上下文
type ThrdSafeMap interface {
	Get(key string) (interface{}, bool)
	GetString(key string) (string, bool)
	GetInt(key string) (int, bool)
	Set(key string, value interface{})
	Remove(key string)
	GetKeys() []string
}
type safemap struct {
	smap map[string]interface{}
	sync.RWMutex
}

func (smap *safemap) GetKeys() []string {
	smap.RLock()
	defer smap.RUnlock()
	mlen := len(smap.smap)
	if mlen == 0 {
		return nil
	}
	res := make([]string, mlen)
	i := 0

	for k := range smap.smap {
		res[i] = k
		i++
	}
	return res
}
func (smap *safemap) Get(key string) (interface{}, bool) {
	smap.RLock()
	defer smap.RUnlock()
	value, ok := smap.smap[key]
	return value, ok
}
func (smap *safemap) Remove(key string) {
	smap.Lock()
	defer smap.Unlock()
	delete(smap.smap, key)
}
func (smap *safemap) GetString(key string) (string, bool) {
	smap.RLock()
	defer smap.RUnlock()
	value, ok := smap.smap[key]
	if ok {
		svalue, oks := value.(string)
		if oks {
			return svalue, true
		}
	}
	return "", false
}

func (smap *safemap) GetInt(key string) (int, bool) {
	smap.RLock()
	defer smap.RUnlock()
	value, ok := smap.smap[key]
	if ok {
		svalue, oks := value.(int)
		if oks {
			return svalue, true
		}
	}
	return 0, false
}

func (smap *safemap) Set(key string, value interface{}) {
	smap.Lock()
	defer smap.Unlock()
	smap.smap[key] = value

}

func CreateSafeMap() ThrdSafeMap {
	return &safemap{
		smap: make(map[string]interface{}),
	}
}
